package com.niedziela12.pai.sessionbeans;

import com.niedziela12.pai.ejb.dto.HotelDTO;
import com.niedziela12.pai.ejb.hotel.endpoints.HotelEndpoint;
import com.niedziela12.pai.ejb.hotel.endpoints.HotelEndpointLocal;
import com.niedziela12.pai.ejb.hotel.facades.HotelFacadeLocal;
import com.niedziela12.pai.sessionbeans.util.JsfUtil;
import com.niedziela12.pai.sessionbeans.util.PaginationHelper;

import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;

@ManagedBean(name = "hotelController")
@SessionScoped
public class HotelController implements Serializable {

    private HotelDTO current;
    private DataModel items = null;
    @EJB
    private HotelEndpointLocal hotelEndpoint;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    
    @ManagedProperty(value = "#{userRights}")
    private UserRights userRights;

    public void setUserRights(UserRights userRights) {
        this.userRights = userRights;
    }

    public HotelController() {
    }
    
    public int getSelectedItemIndex(){
        return selectedItemIndex;
    }

    public HotelDTO getSelected() {
        if (current == null) {
            current = new HotelDTO();
            selectedItemIndex = -1;
        }
        return current;
    }
    
    public void destroySelection(){
        current = new HotelDTO();
        selectedItemIndex = -1;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return hotelEndpoint.getHotelsCount();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(hotelEndpoint.getHotels(getPageFirstItem(), getPageFirstItem() + getPageSize()));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return userRights.isAdmin() ? "adminListHotels" : "otherListHotels";
    }

    public String prepareView() {
        current = (HotelDTO) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return userRights.isAdmin() ? "adminViewHotels" : "otherViewHotels";
    }

    public String prepareCreate() {
        current = new HotelDTO();
        selectedItemIndex = -1;
        return "adminAddHotel";
    }

    public String create() {
        try {
            hotelEndpoint.addNewHotel(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("HotelCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (HotelDTO) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "adminEditHotel";
    }

    public String update() {
        try {
            hotelEndpoint.updateHotelInfo(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("HotelUpdated"));
            return "adminViewHotels";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String destroy() {
        current = (HotelDTO) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "adminListHotels";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "adminViewHotels";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "adminListHotels";
        }
    }

    private void performDestroy() {
        try {
            hotelEndpoint.deleteHotel(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("HotelDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
        }
    }

    private void updateCurrentItem() {
        int count = hotelEndpoint.getHotelsCount();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = hotelEndpoint.getHotels(selectedItemIndex, selectedItemIndex+1).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return userRights.isAdmin() ? "adminListHotels" : "otherListHotels";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return userRights.isAdmin() ? "adminListHotels" : "otherListHotels";
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(hotelEndpoint.getAllHotels(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(hotelEndpoint.getAllHotels(), true);
    }

    @FacesConverter(forClass = HotelDTO.class)
    public static class HotelControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            HotelController controller = (HotelController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "hotelController");
            return controller.hotelEndpoint.getHotel(getKey(value));
        }

        java.lang.Long getKey(String value) {
            java.lang.Long key;
            key = Long.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Long value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof HotelDTO) {
                HotelDTO o = (HotelDTO) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + HotelDTO.class.getName());
            }
        }
    }
}
